﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CHGK.web.UI;
using CHGK.web.UI.Models;
using ChGK.Data;

namespace CHGK.web.UI.Controllers
{
    public class TeamController : Controller, IDisposable
    {
        //
        // GET: /Team/
        private DataManager _DataManager;
        
        public TeamController()
        {
            _DataManager = new DataManager();
        }

        [HttpGet]
        [Authorize(Roles = "User")]
        public ActionResult TeamPage(int TourNumber, short QuestionNumber)
        {
            User _User = _DataManager.Users.GetUser(User.Identity.Name);

            int _TourNumber = TourNumber;

            Competition _Competition = _DataManager.Competitions.GetCompetitionByUserLogin(_User.Login);
            Tour _Tour = _DataManager.Tours.GetTour(_Competition.ID, _TourNumber);
            short _QuestionNumber = QuestionNumber;
            Team _Team = _DataManager.Teams.GetTeam((int)_User.TeamID);

            if (QuestionNumber == 1)
            {
                _QuestionNumber = (short)(_QuestionNumber - _Tour.NumberOfNullQuestions);
            }

            while (_DataManager.Answers.GetAnswer(_Team.ID, _Tour.ID, _QuestionNumber) != null)
            {
                if (_QuestionNumber < _Tour.NumberOfQuestions)
                {
                    _QuestionNumber++;

                }
                else
                {
                    _TourNumber++;
                    _Tour = _DataManager.Tours.GetTour(_Competition.ID, _TourNumber);
                    if (_Tour != null)
                    {
                        _QuestionNumber = (short)(1 - _Tour.NumberOfNullQuestions);
                    }
                    else
                    {
                        return RedirectToAction("TeamOver", "Team");
                    }
                }
            }

            ViewData["Team"] = _Team.Caption;
            ViewData["TourNumber"] = _Tour.NumberInCompetition;
            ViewData["TourID"] = _Tour.ID;
            ViewData["Question"] = _QuestionNumber;
            ViewData["Answers"] = _DataManager.Answers.GetAnswers(_Team, _Tour);
            
            string sKey = _User.Login;
            string sUser = Convert.ToString(System.Web.HttpContext.Current.Cache[sKey]);
            
            if (sUser == null || sUser == String.Empty)
            {
                //устанавливаем срок устаревания кеша
                TimeSpan SessTimeOut = new TimeSpan(0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0);
                System.Web.HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);
                //Записываем в кеш сессии логин пользователя
                Session["user"] = _User.Login;
            }

            return View();
        }

        [HttpPost]
        [Authorize(Roles = "User")]
        public ActionResult TeamPage(string Team, int TourNumber, int TourID, int Question, string Answer)
        {
            User _User = _DataManager.Users.GetUser(User.Identity.Name);
            Competition _Competition = _DataManager.Competitions.GetCompetitionByUserLogin(_User.Login);
            Team _Team = _DataManager.Teams.GetTeam((int)_User.TeamID);

            if (Answer == "")
            {
                ModelState.AddModelError("Answer", "Поле для ответа не может быть пустым. Если Вы хотите отправить 'пустой' ответ, добавьте пробел");

            }
            if (ModelState.IsValid)
            {
                Answer _Answer = _DataManager.Answers.GetFirstAnswer(TourID, Question);
                if (_Answer == null || _Answer.isLate == null)
                {
                    _DataManager.Answers.CreateAnswer(Answer, (short)Question, true, TourID, _Team.ID);
                }
                else
                {
                    _DataManager.Answers.CreateAnswer(Answer, (short)Question, true, TourID, _Team.ID, true);
                }

                return RedirectToAction("TeamPage", new { TourNumber = TourNumber, QuestionNumber = Question });
            }

            ViewData["Team"] = _Team.Caption;
            ViewData["Tour"] = TourNumber;
            ViewData["Question"] = Question;
            return View();
        }

        public ActionResult TeamOver()
        {
            return View();
        }

    }
}
